<?php

namespace App\Http\Controllers\BaseData;

use App\Http\Controllers\Controller;
use App\Models\Dict;
use App\Models\Category;

class DictController extends Controller
{

    use \App\Http\Extend\TraitCategory;
    public function index()
    {
        if (post('?')) {
            $_category = post("_category");
            return (Dict::where("category_id", $_category)->relatedJoin()->getGrid());
        } else {
            $param = F();
            $param['categroy'] = $this->CategoryAll();
            return view('BaseData.DictController.index',  $param);
        }
    }
    public function add()
    {
        $_category = get('_category');
        if (post('?')) {
            $data = post('data');

            try {
                begin();
                Dict::create(unsetNull($data));
                commit();
            } catch (\Exception $e) {
                rollback();
                return error($e->getMessage());
            }

            return success("保存成功！");
        } else {
            $param['gdata']['category'] = Category::where("id", $_category)->first();
            return view('BaseData.DictController.add',  $param);
        }
    }

    public function edit()
    {
        $id = get('id');
        $gdata = Dict::where(['id' => $id])->with("category")->first();

        if (post('?')) {
            $data = post('data');
            try {
                begin();
                $gdata->update(unsetNull($data));
                commit();
            } catch (\Exception $e) {
                rollback();
                return error($e->getMessage());
            }
            return success("保存成功！");
        } else {
            // $param = F();
            $param['gdata'] = $gdata;
            return view('BaseData.DictController.add',  $param);
        }
    }

    public function delete()
    {
        begin();
        $ids = request()->post('ids');;
        // Category::whereIn("id", $ids)->delete();
        foreach (Dict::whereIn("id", $ids)->get() as  $k => $v) {
            //判断能否删除
            $v->delete();
        }
        commit();
        return success("删除成功！");
    }
}
